package com.goodsogood.union.auth.conf;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 配置文件加载器
 * @author liuy
 *
 */
public class ConfigLoader {
    
    static final Logger logger = LoggerFactory.getLogger(LogConfiger.APP);
    
    private static final String configFile = "conf/config.properties";
    
    private static Properties properties = new Properties();
    
    private static ConfigLoader instance = null;
    
    private static synchronized void initInstance() {
        if (instance == null) {
            instance = new ConfigLoader();
            load();
        }
    }
    
    public static String getValue(String key) {

        if (key == null || "".equals(key)) {
            return "";
        }

        if (instance == null) {
            initInstance();
        }
        
        return properties.getProperty(key);
    }
    
    private static void load() {
        
        BufferedReader br = null;
        InputStream input = null;
        try {
            
            input = ConfigLoader.class.getClassLoader().getResourceAsStream(configFile);
            
            if(input == null) {
                logger.error("properties file {} don't exist:", configFile);
                return;
            }
            
//            File f = new File(configFile);
//            if(!f.exists()) {
//                logger.error("properties file {} don't exist:", configFile);
//                return;
//            }
//            input = new FileInputStream(configFile);
            
            br = new BufferedReader(new InputStreamReader(input, "UTF-8"));
            properties.load(br);
        } catch (IOException e) {
            logger.error("load properties fail :", e);
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    //ignore
                }
            }
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    //ignore
                }
            }
        }
    }
}
